$j(document).ready(function () {
	
});	

//自动以的setTimeout方法，可传递参数
function masterSetTimeout(callback,timeout,param)
{
    var args = Array.prototype.slice.call(arguments,2);
    var _cb = function()
    {
        callback.apply(null,args);
    }  
    window.setTimeout(_cb,timeout);
}



function associatedBulkEditSave(){
	var confirmMsg = __FMT.common_message_confirmSaveThis+"?";
	if(validateAction()){
    	if (!confirmMsg || confirm(confirmMsg)) {
	    	var url = document.productForm.action+"?doAction=associatedBulkEditSave";
	    	var postData = $j('#productForm :input').serialize();
			$j.post(url,postData,associatedBulkEditSaveCallback,"json");
	    }
    }
}

function associatedBulkEditSaveCallback(data){
	if(data.error && data.error!=""){
		jAlert(data.error);
		return ;
	}
	
	 sysMsg(__FMT.associateBulkEdit_commit_success);
	 
	 if (data.newSkuIds) {
		for (var i = 0; i < data.newSkuIds.length; i++) {
			$j("#" + data.oldSkuIds[i]).val("skuId_"+data.newSkuIds[i]);
			$j("#" + data.oldSkuIds[i]).attr("id","skuId_"+data.newSkuIds[i]);
		}
	}
	
	if (data.newWpIds) {
		for (var i = 0; i < data.newWpIds.length; i++) {
			$j("#" + data.oldWpIds[i]).val("wpId_"+data.newWpIds[i]);
			$j("#" + data.oldWpIds[i]).attr("id","wpId_"+data.newWpIds[i]);
		}
	}
	if (data.newWpSkuIds) {
		for (var i = 0; i < data.newWpSkuIds.length; i++) {
			$j("#" + data.oldWpSkuIds[i]).val("wpskuId_"+data.newWpSkuIds[i]);
			$j("#" + data.oldWpSkuIds[i]).attr("id","wpskuId_"+data.newWpSkuIds[i]);
		}
	}
	
}


var skuCounter=0;
var wholesalePriceCounter=0;

//增加sku
// tableDivId 是product所对应的skuTable
// sku 是一个JSON对象{id,code,imageUrl}

function addSku(tableDivId,sku){
	var id,code,mediaUrl,src;
	var listPrice,price,salePrice,weight,inventory;
	var optionValueInfo;
	if(null == sku){
		skuCounter++;
		id = "new_"+skuCounter;//包含表示新增
		code = "";
		mediaUrl=__defaultImage_m0;
		src ="";
		listPrice = "";
		price = "";
		salePrice = "";
		weight = "";
		inventory = "";
		optionValueInfo = "";
		
	}else{
		id = "_"+sku.id;
		code = sku.code;
		mediaUrl = sku.imageUrl;
		src = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s1"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
		listPrice = sku.listPrice;
		price = sku.price;
		salePrice =  sku.salePrice;
		weight =  sku.weight;
		inventory =  sku.inventory;
		optionValueInfo = sku.optionValueInfo;
	}
	var html="";
	html += '<div class="content" id="sku'+id+'">';
	html += '<div class="circle_corner_block1"><div class="circle_corner_block2"><div class="circle_corner_block3"><div class="cnt">';
	//---start：操作区---
	html += '<div class="do">';
	html += '</div>';
	//---end：  操作区---
	
	html += '<table class="sku_table_wrap"><tr>';
	//---start：概况区---
	html += '<td class="multiSku" valign="top">';
	html += '<table class="sku_table">';
	
	
	html += '<tr>';
	//---start：规格项选择区 与productForm.js区别的地方---
	html += '<td valign="top"><div class="sku">';
	
	html += '<ul class="now">';
	for(var i=0; i< sku.skuOptionInfoJson.length; i++){
		html += '<li class="skuOptionValueLi">';
		html += '<em>'+getSelectedOptionValueDiv(sku.skuOptionInfoJson[i].skuOptionValue)+'</em>';
		html += sku.skuOptionInfoJson[i].skuOption.name;
		html += '</li>';
	}
	html += '</ul>';
	
	html += '</div></td>';
	//---end：  规格项选择区---
	
	//---start：单品图片区---
	html += '<td valign="top"><div class="img_wrap">';
	if(mediaUrl==""){
		html += '<a href="javascript:void(0)">';
	}else{
		html += '<a href="'+__mediaPath +mediaUrl+'" target="_blank">';
	}
	html += '<img id="skuImage'+id+'" src="' + src+ '" width="115" height="115" onerror="this.src=__defaultImage;this.onerror=\'\'" />';
	html += '</a>';
	html += '</div>';
	html += '</td>';
	//---end：  单品图片区---
	
	html += '</tr>';
	
	
	html += '</table>';
	html += '</td>';
	//---end：  概况区---
	
	//---start：销售区---
	html += '<td valign="top">';
	html += '<ul id="accordion'+id+'" style="width:450px;">';
		
	//---start：基本销售信息
	html += '<li> <h3>'+__FMT.productForm_basicPrice+'</h3> <table class="normal_table1">';
	html += '<tr>';
	html += '<th>'+__FMT.productSku_listPrice+':</th><td><input type="text" id="listPrice'+id+'" name="listPrices" value="'+listPrice+'"  class="inputtxt" style="width:120px;"/></td>';
	html += '<th>'+__FMT.productSku_productSkuCode+':</th><td>'+code+'</td>';
	html += '</tr>';
	html += '<tr>';
	html += '<th>'+__FMT.productSku_price+'(<span class="red">*</span>):</th><td><input type="text" id="price'+id+'"  name="prices" value="'+price+'" class="inputtxt" style="width:120px;"/></td>';
	html += '<th>'+__FMT.productSku_inventory+':</th><td><input type="text"  id="inventory'+id+'" name="inventorys" value="'+inventory+'" class="inputtxt" style="width:120px;"/></td>';
	html += '</tr>';
	html += '<tr>';
	html += '<th>'+__FMT.productSku_salePrice+':</th><td><input type="text"  id="salePrice'+id+'" name="salePrices" value="'+salePrice+'" class="inputtxt" style="width:120px;"/></td>';
	html += '<th>'+__FMT.productSku_weight+':</th><td><input type="text" id="weight'+id+'"  name="weights" value="'+weight+'" class="inputtxt" style="width:120px;"/>(g)</td>';
	html += '</tr>';
	html += '</table ></li>';
	//---end：基本销售信息
	
	
	//批发价开始
	html += '<li> <h3>'+__FMT.productForm_wholesalePrice+'</h3> <div class="list_price">';
	html += '<table  class="normal_table2">';
	html += '<th>'+__FMT.wholesalePrice_minQuantity+'</th>';
	html += '<th>'+__FMT.wholesalePrice_maxQuantity+'</th>';
	html += '<th>'+__FMT.wholesalePrice_price+'</th>';
	html += '<th>'+__FMT.wholesalePrice_delete+'</th>';
	html += '</table>';
	html += '<div class="price_wrap"><table class="normal_table3" id="wholesalePriceTable'+id+'"></table></div>';
	html += '<div class="add_wrap"><a class="add_price" href="javascript:void(0)" onclick="addWholesalePrice(\'wholesalePriceTable'+id+'\',null)"></a></div>';
	html += '</div></li>';
	//批发价结束
	
	html += '</ul>';
	html += '</td>';
	//---end：  销售区---
	
	html += '</tr></table>';
	
	
	html += '</div></div></div></div>';
	//start:hidden
	html += '<input type="hidden" name="skuIds" value="skuId'+id+'" id="skuId'+id+'"/>';
	//end:hidden
	
	html += '</div>';
	$j('#'+tableDivId).append(html);
	
	//$j("#accordion"+id).accordion({header:"h3",animated:false});
	//使用定时器方式来加载 增加速度
	masterSetTimeout(initAccordion,20,id);
	return "wholesalePriceTable"+id;
}


//初始化accordion
function initAccordion(id){
	$j("#accordion"+id).accordion({header:"h3",animated:false});
}


//设置已选择的规格值区 skuOptionValue是一个json对象{id,name,value,type}
function getSelectedOptionValueDiv(skuOptionValue){
	html = "";
	if(skuOptionValue.type == 1){
		html += '<b class="txt" title="'+skuOptionValue.name+'">';
		html += skuOptionValue.value;
		html += '</b>';
	}else if(skuOptionValue.type == 2){
		html += '<b style="background-color:#'+skuOptionValue.value+'" title="'+skuOptionValue.name+'">';
		html += '</b>';
		
	}else if(skuOptionValue.type == 3){
		html += '<b style="background-image:url('+__mediaPath+skuOptionValue.value+')" title="'+skuOptionValue.name+'">';
		html += '</b>';
	}else{}
	return html;
}


//增加批发价
// tableDivId 是批发价所对应的wholesalePriceTable;
// wholesalePrice是一个JSON对象{wpId,wpSkuId,wpMinQuantity,wpMaxQuantity,wpPrice,wpDeliveryDay};
function addWholesalePrice(tableDivId,wholesalePrice){
	var id,skuId,minQuantity,maxQuantity,price,deliveryDay;
	var isFirst = true;
	var lastMaxQuantity = $j('.maxQuantity:last','#'+tableDivId);
	if(lastMaxQuantity.size() == 0){
		isFirst = true;
	}else{
		isFirst = false;
	}
	if(null == wholesalePrice){
		wholesalePriceCounter++;
		id = "new_"+wholesalePriceCounter; //new前缀表示新增
		
		
		if(!isFirst){
			//start:获得上一个最大值,并设置下一个最小值
			if(null != lastMaxQuantity && lastMaxQuantity.val()!= "" ){
				if(isNotNegativeInteger(lastMaxQuantity.val())){
					minQuantity = ""+(parseInt(lastMaxQuantity.val())+1);
				}else{
					jAlert(__FMT.productForm_signNotNegativeNum);
					lastMaxQuantity.get(0).focus();
				return;
				}	
			}else{
				jAlert(__FMT.productForm_signLastMaxQuantity);
				lastMaxQuantity.get(0).focus();
				return;
			}	
			//end:获得上一个最大值,并设置下一个最小值
			
		}else{
			minQuantity = "1";
		}	
		maxQuantity = "";
		price = "";
		deliveryDay = "";
	}else{
		id = "_"+wholesalePrice.wpId;
		minQuantity = wholesalePrice.wpMinQuantity;
		maxQuantity = wholesalePrice.wpMaxQuantity;
		price = wholesalePrice.wpPrice;
		deliveryDay = wholesalePrice.wpDeliveryDay;
	}
	var skuTr = $j('#'+tableDivId).parents(".content");
	var skuIdInput = $j('input[name="skuIds"]',skuTr);
	skuId = "wp"+skuIdInput.val();
	//将上一个的delete 链接隐藏
	var lastDelete = $j('.deleteWholesalePrice:last','#'+tableDivId);
	lastDelete.hide();
	
	var html = "";
	html += '<tr id="wholesalePrice'+id+'" >';
	if(isFirst){
		html += '<td ><input style="width:100px;" class="minQuantity inputtxt" id="wpMinQuantity'+id+'"  name="wpMinQuantitys" value="'+minQuantity+'" onchange="wpMinQuantityHandler(\''+id+'\')"/></td>';
	}else{
		html += '<td ><span>'+minQuantity+'</span><input type="hidden" class="minQuantity" id="wpMinQuantity'+id+'" name="wpMinQuantitys" value="'+minQuantity+'"/></td>';
	}
	html += '<td ><input style="width:100px;" class="maxQuantity inputtxt" id="wpMaxQuantity'+id+'" name="wpMaxQuantitys" value="'+maxQuantity+'"  onchange="wpMaxQuantityHandler(\''+id+'\')"/></td>';
	html += '<td ><input style="width:100px;" class="inputtxt" id="wpPrice'+id+'" name="wpPrices" value="'+price+'"/></td>';
	html += '<td ><a class="deleteWholesalePrice del_price" href="javascript:void(0)" onclick="delWholesalePrice(\''+tableDivId+'\',\'wholesalePrice'+id+'\')" ><b>&nbsp;</b></a></td>';
	//start:hidden
	html += '<input type="hidden" name="wpIds" id="wpId'+id+'" value="wpId'+id+'"/>';
	html += '<input type="hidden" name="wpSkuIds" id="'+skuId+'" value="'+skuId+'"/>';
	//end:hidden
	html += '</tr>';
	$j('#'+tableDivId).append(html); 
	
}
//删除批发价
// tableDivId 是批发价所对应的wholesalePriceTable;
// trDivId 是批发价所对应的wholesalePriceTr;
function delWholesalePrice(tableDivId,trDivId){
	$j('#'+trDivId).remove();
	//将上一个的delete 链接显示
    var lastDelete = $j('.deleteWholesalePrice:last','#'+tableDivId);
    lastDelete.show();
}

//改变到按规格定价 即允许多个sku
// tableDivId 是sku所对应的skuTable
function changeToMultiSkus(tableDivId){
	$j('.multiSku','#'+tableDivId).show();
}
//改变到单sku
// tableDivId 是sku所对应的skuTable
function changeToSingleSku(tableDivId){
	$j('.multiSku','#'+tableDivId).hide();
	
}


//验证函数
function validateAction(){	

	//remove all the red
	$j(".x-form-invalid + img").remove();	
	$j(".x-form-invalid").attr("class","");	
	
	var flag = true;
	
	//start:validate apply
	
	$j('input[name="listPrices"]').each(function(index,obj){
		applyValidate(obj,"price");
	});
	$j('input[name="prices"]').each(function(index,obj){
		applyValidate(obj,"price,required");
	});
	$j('input[name="salePrices"]').each(function(index,obj){
		applyValidate(obj,"price");
	});
	$j('input[name="weights"]').each(function(index,obj){
		applyValidate(obj,"floatRange=[0-100000]");
	});
	$j('input[name="inventorys"]').each(function(index,obj){
		applyValidate(obj,"integer,intRange=[0-100000]");
	});
	
	
	$j('input[name^="wpPrices"]').each(function(index,obj){
		applyValidate(obj,"price,required");
	});
	$j('input[name^="wpMinQuantitys"]').each(function(index,obj){
		if(flag){
			if("" == obj.value.trim() || !isNotNegativeInteger(obj.value.trim())){
				problemQuantity = obj;
				setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
				jAlert(__FMT.productForm_signNotNegativeNum);
				flag = false;
			}
		}
	});
	$j('input[name^="wpMaxQuantitys"]').each(function(index,obj){
		if(flag){
			if("" == obj.value.trim() || !isNotNegativeInteger(obj.value.trim())){
				problemQuantity = obj;
				setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
				jAlert(__FMT.productForm_signNotNegativeNum);
				flag = false;
			}
		}
	});
	$j('input[name^="wpMaxQuantitys"]').each(function(index,obj){
		if(flag){
			var maxQuantity= obj.value;
			var temp = $j(obj).parent("td:first");
			var temp2 = $j(obj).parent("td:first").prev();
			var minQuantity= $j(obj).parent("td:first").prev().children(".minQuantity").get(0).value;
			if(!isLargerEqual(maxQuantity,minQuantity)){
				problemQuantity = obj;
				setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
				jAlert(__FMT.productForm_incorrectMaxQuantity);
				flag = false;
				
			}
		}
	});
   

	//end:validate apply
	
	 if(flag){
		 if(!validateProduct($j("#productForm")[0])){
	    	flag = false;
	   	}
   	}
  
   	return flag;
}


//改变截止购买数量的handler
var problemQuantity;  //问题所在的quantity
function wpMaxQuantityHandler(id){
	var obj = $j('.maxQuantity:last','#wholesalePrice'+id);
	if(!isNotNegativeInteger(obj.val())){
		jAlert(__FMT.productForm_signNotNegativeNum);
		obj.val("");
		problemQuantity = obj.get(0);
		setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住

	}else{
		var nextMinQuantity =obj.parent("td").parent("tr").next().find('.minQuantity');
		if(nextMinQuantity.size()!=0){
			nextMinQuantity.val(parseInt(obj.val())+1);
			nextMinQuantity.prev("span").html(nextMinQuantity.val());
		}
	}
}

//改变起始购买数量的handler
function wpMinQuantityHandler(id){
	var obj = $j('.minQuantity:last','#wholesalePrice'+id);
	if(!isNotNegativeInteger(obj.val())){
		jAlert(__FMT.productForm_signNotNegativeNum);
		$j(this).val("");
		problemQuantity = obj.get(0);
		setTimeout("problemQuantity.focus();", 0);//必须用这种方法才能focus住
	}else{
	}
}

//判断str1是否大于str2, str1和str2都是字符串值
function isLargerEqual(str1,str2){
	return parseInt(str1)>=parseInt(str2);
}	
//是否非负整数 str是一个字符串值
function isNotNegativeInteger(str){
	var regExp = new RegExp("^(([1-9][0-9]*)|0)$");
	return regExp.test(str);
}


/**
 * 初始化upload控制
 * @param {Object} fileInputId 需上传的Input
 * @param {Object} uploadCategory 上传文件保存的目录
 * @param {Object} supportedSuffixs 支持的后缀，多个逗号隔开，空表示不限制
 * @param {Object} nonsupportedSuffixs不支持的后缀，多个逗号隔开，空表示不限制
 * @param {Object} onCompleteHandler 上传成功后的回调，返回来个参数，一个是上传后的文件路径，另一个是需上传的Input ID
 */
function initUpload(fileInputId, uploadCategory, supportedSuffixs, nonsupportedSuffixs, onCompleteHandler){
	var urlAction = '/dialog/upload.html?uploadCategory=' + uploadCategory + "&fileInputId=" + fileInputId;
	if (onCompleteHandler) 
		urlAction += "&onCompleteHandler=" + onCompleteHandler.toLocaleString().substring(9, onCompleteHandler.toLocaleString().indexOf("("));
	var plugin_upload_valid = true;
	$j("<input type='button' class='upload_img_2' />").insertAfter("#" + fileInputId).upload({
		name: 'file',
		action: __ctxPath + urlAction,
		enctype: 'multipart/form-data',
		params: {},
		onSubmit: function(){
			return plugin_upload_valid;
		},
		onComplete: function(){
		},
		onSelect: function(){
			plugin_upload_valid = true;
			var idx = this.filename().lastIndexOf(".");
			if (idx == -1 || idx >= this.filename().length) {
				plugin_upload_valid = false;
			}
			var suffix = this.filename().substring(idx + 1, this.filename().length).toLowerCase();
			if (plugin_upload_valid && supportedSuffixs) {
				plugin_upload_valid = (supportedSuffixs.toString().indexOf(suffix) >= 0);
			}
			if (plugin_upload_valid && nonsupportedSuffixs) {
				plugin_upload_valid = (nonsupportedSuffixs.toString().indexOf(suffix) == -1);
			}
			if (!plugin_upload_valid) {
				jAlert(__FMT.error_upload_unsupport + ":" + supportedSuffixs.toString());
				return false;
			}
		},
		autoSubmit: true
	});
	$j("#" + fileInputId).wrap("<div style='float:left;'></div>");
}




